package cmd

import (
	"fmt"
	"io/ioutil"
	"md5util/util"
	"os"
	"path"
	"strings"
	"time"

	"github.com/olekukonko/tablewriter"
	"github.com/spf13/cobra"
)

var md5dirCmd = &cobra.Command{
	Use:   "dir",
	Short: "目录MD5",
	Long:  `生成目录中所有文件的MD5`,
	Run: func(cmd *cobra.Command, args []string) {
		upper, _ := cmd.Flags().GetBool("upper")
		table := tablewriter.NewWriter(os.Stdout)
		table.SetHeader([]string{"NAME", "MD5", "SIZE", "SPENT(ms)"})
		defer table.Render()

		dir := strings.Join(args, " ")
		fmt.Println(dir)
		files, err := ioutil.ReadDir(dir)
		if err != nil {
			fmt.Println(err)
			return
		}

		for _, f := range files {
			if !f.IsDir() {
				start := time.Now()
				filepath := path.Join(dir, f.Name())
				md5str, bsize, err := util.MD5File(filepath, upper)
				spent := fmt.Sprintf("%d", time.Since(start).Milliseconds())
				if err != nil {
					fmt.Println(err)
				} else {
					table.Append([]string{f.Name(), md5str, bsize, spent})
				}
			}
		}
	},
}

func init() {
	rootCmd.AddCommand(md5dirCmd)
}
